package cn.edu.gcu.giftems.daos;

import cn.edu.gcu.giftems.pojos.Strategy;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.query.Query;
import org.springframework.orm.hibernate5.HibernateCallback;
import org.springframework.orm.hibernate5.support.HibernateDaoSupport;

import java.util.List;

/**
 * 攻略Dao类.
 *
 * @author ZhengHQ
 * @create 2018-09-24
 * @see
 */
public class StrategyDao extends HibernateDaoSupport {
    
    //获取攻略总记录
    public int findCount() {
        String hql = "select count(*) from Strategy";
        //List list=new ArrayList();
        List<Long> list = (List<Long>)this.getHibernateTemplate().find(hql);
        if(list.size() > 0){
            return list.get(0).intValue();
        }
        return 0;
    }
    //获取攻略集合信息
    public List<Strategy> findByPage(int begin, int pageSize) {
        DetachedCriteria criteria = DetachedCriteria.forClass(Strategy.class);
        List<Strategy> list = (List<Strategy>)this.getHibernateTemplate().findByCriteria(criteria, begin, pageSize);
        return list;
    }
    //添加攻略
    public void save(Strategy strategy) {
        this.getHibernateTemplate().save(strategy);
    }
    
    //根据攻略编号查询攻略信息
    public Strategy finById(int id) {
        return this.getHibernateTemplate().get(Strategy.class,id);
    }
    
    //更新攻略信息
    public void update(Strategy strategy) {
        this.getHibernateTemplate().update(strategy);
    }
    
    //根据攻略id删除攻略
    public void delete(Strategy strategy) {
        this.getHibernateTemplate().delete(strategy);
    }

    public List<Strategy> findAll() {
        String hql = "from Strategy";
        return (List<Strategy>)this.getHibernateTemplate().find(hql);
    }

    public List<Strategy> findByParameter(String filter_name, String simple_filter_value) {
        List<Strategy> list = null;
        String hql = "from Strategy s where " + filter_name + " like '%" + simple_filter_value + "%'";
        try {
            list = (List<Strategy>) this.getHibernateTemplate().execute(
                    new HibernateCallback<Object>() {
                        public Object doInHibernate(Session arg0)
                                throws HibernateException {
                            Query query = arg0.createQuery(hql);
                            return query.list();
                        }
                    }
            );
        } catch (RuntimeException re) {
            throw re;
        }
        return list;
    }
}
